package com.ezjie.baselib.core.http;

import java.io.File;
import java.util.Map;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.ezjie.baselib.core.base.HttpHeaderBean;
import com.ezjie.baselib.spfs.SharedPrefHelper;
import com.ezjie.baselib.util.LogUtils;
import com.ezjie.baselib.util.SystemUtils;
import com.igexin.sdk.PushManager;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * Http请求类 * @author renyangyang
 *
 */
public class HttpAPI {
	/**设置超时时间*/
	private String uid;
	private String login_key;
    private static final int TIME_OUT = 1000 * 10;
    private static final boolean USESSL = false;
    static String FUNCATION;
    private static HttpAPI httpUtil ; 

    private final HttpUtils http = new HttpUtils();  

    private final String mApiBaseUrl;
    private static Context mContext;

    public static String getScheme(){
        return USESSL ? "https://" : "http://";
    }

    private HttpAPI(Context context) {
        super();
        mApiBaseUrl = getScheme() + FUNCATION;
    }
    
    public static HttpAPI getInstance(Context context,String API_PATH){
    	mContext = context;
    	FUNCATION=API_PATH;
    	if(httpUtil==null){
    		httpUtil = new HttpAPI(context);
    	}
    	return httpUtil;
    }
    
    private RequestParams addQueryStringParameter(Map<String, String> params){
    	RequestParams requestParams = new RequestParams();
    	requestParams.addHeader("parameters", requestParameters());
		if (params != null) {
			if (!params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
					
					LogUtils.d( "Param: " + entry.getKey()+":" + entry.getValue());
					requestParams.addQueryStringParameter(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
				}
			}
		}  
		
        return requestParams;
    }
    
    private RequestParams assemblyPostRequestParams(Map<String, String> params,Map<String, File> files){
    	RequestParams requestParams = new RequestParams();
    	requestParams.addHeader("parameters", requestParameters());
		if (params != null) {
			if (!params.isEmpty()) {
				for (Map.Entry<String, String> entry : params.entrySet()) {// 构建表单字段内容
					LogUtils.d( "Param: " + entry.getKey()+":" + entry.getValue());
					requestParams.addBodyParameter(entry.getKey(), entry.getValue() == null ? "" : entry.getValue());
				}
			}
		}  
		
		if (files != null) {
			if (!files.isEmpty()) {
				for (Map.Entry<String, File> entry : files.entrySet()) {// 构建表单字段内容
					
					LogUtils.d( "Param: " + entry.getKey()+":" + entry.getValue());
					requestParams.addBodyParameter(entry.getKey(), entry.getValue());
				}
			}
		} 
		
        return requestParams;
    }
	public String requestParameters() {
		HttpHeaderBean headerBean = new HttpHeaderBean();
		headerBean.setApp_name("ezjie.android.ieltsezj");
		headerBean.setApp_version(SystemUtils.getVersion(mContext));
		headerBean.setCid(PushManager.getInstance().getClientid(mContext));
		headerBean.setDevice(SystemUtils.getBrand(mContext));
		headerBean.setDevice_id(SystemUtils.getIMEI(mContext));
		headerBean.setDevice_token("");
		headerBean.setLogin_key(SharedPrefHelper.getInstance().isLoginkey());
		headerBean.setNationality(mContext.getResources().getConfiguration().locale.getCountry());
		headerBean.setSystem("Android");
		headerBean.setSystem_version(SystemUtils.getSystemVersion());
		headerBean.setUid(SharedPrefHelper.getInstance().isLoginUid());
		headerBean.setVersion_code(SystemUtils.getVersionCode(mContext));

		String jsonStr = JSONObject.toJSON(headerBean).toString();
		LogUtils.d("parameters:" + jsonStr);
		return jsonStr;
	}
    public String requestCookieKey() {
		StringBuilder sb = new StringBuilder();
		
		try {
			sb.append("app_version=").append(SystemUtils.getVersion(mContext))
			.append(";system_version=").append(SystemUtils.getSystemVersion())
			.append(";system=").append("Android")
			.append(";device=").append(SystemUtils.getBrand(mContext))
			.append(";device_id=").append(SystemUtils.getIMEI(mContext))
			.append(";nationality=").append(mContext.getResources().getConfiguration().locale.getCountry())
			.append(";Accept-Language=").append(SystemUtils.getLanguage());
			
			LogUtils.d("cookie:"+sb.toString());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}

    
    private String fullUrl(String url) {
        return mApiBaseUrl + url;

    }
    /**
     * 发送GET请求
     * @param path
     * @param params
     * @param httpRequestCallback
     */
	public HttpHandler<String> doGetRequest(String path,Map<String, String> params,final HttpRequestCallBack httpRequestCallback){  
        http.configCurrentHttpCacheExpiry(TIME_OUT);//设置超时时间  
        LogUtils.d(fullUrl(path));
        return http.send(HttpMethod.GET, fullUrl(path), addQueryStringParameter(params), new RequestCallBack<String>() {//接口回调  
        	@Override
        	public void onStart() {
        		httpRequestCallback.onStartCallBack();
        	}
        	
        	@Override
        	public void onLoading(long total, long current, boolean isUploading) {
        		httpRequestCallback.onLoadingCallBack(total, current, isUploading); 
        	}
        	
            @Override  
            public void onFailure(HttpException error, String msg) {  
                httpRequestCallback.onFailureCallBack(error, msg);  
            }  
  
            @Override  
            public void onSuccess(ResponseInfo<String> info) {  
            	httpRequestCallback.onSuccessCallBack(info.result);
            }  
        });      	 
    }
	/**
	 * 发送POST请求
	 * @param path
	 * @param params
	 * @param httpRequestCallback
	 */
	public void doPostRequest(String path,Map<String, String> params,final HttpRequestCallBack httpRequestCallback){
        http.configCurrentHttpCacheExpiry(TIME_OUT);//设置超时时间
        LogUtils.d(fullUrl(path));
        
        http.send(HttpMethod.POST, fullUrl(path), assemblyPostRequestParams(params,null), new RequestCallBack<String>() {//接口回调  
        	@Override
        	public void onStart() {
        		httpRequestCallback.onStartCallBack();
        	}
        	
        	@Override
        	public void onLoading(long total, long current, boolean isUploading) {
        		httpRequestCallback.onLoadingCallBack(total, current, isUploading); 
        	}
        	
            @Override  
            public void onFailure(HttpException error, String msg) {  
                httpRequestCallback.onFailureCallBack(error, msg);  
            }  
  
            @Override  
            public void onSuccess(ResponseInfo<String> info) {  
                httpRequestCallback.onSuccessCallBack(info.result);
            } 
        });      	    	
    }
	
	/**
	 * 上传文件
	 * @param path
	 * @param params
	 * @param files
	 * @param httpRequestCallback
	 */
	public void doUploadRequest(String path,RequestParams params,final HttpRequestCallBack httpRequestCallback){
        http.configCurrentHttpCacheExpiry(TIME_OUT);//设置超时时间  
        LogUtils.d(fullUrl(path));
        
        http.send(HttpMethod.POST, fullUrl(path),params, new RequestCallBack<String>() {//接口回调  
        	@Override
        	public void onStart() {
        		httpRequestCallback.onStartCallBack();
        	}
        	
        	@Override
        	public void onLoading(long total, long current, boolean isUploading) {
        		httpRequestCallback.onLoadingCallBack(total, current, isUploading); 
        	}
        	
            @Override  
            public void onFailure(HttpException error, String msg) {  
                httpRequestCallback.onFailureCallBack(error, msg);  
            }  
  
            @Override  
            public void onSuccess(ResponseInfo<String> info) {  
                httpRequestCallback.onSuccessCallBack(info.result);
            }  
        });      	
       
    }
	/**
	 * 上传文件
	 * @param path
	 * @param params
	 * @param files
	 * @param httpRequestCallback
	 */
	public void doUploadFileRequest(String path,Map<String, String> params,Map<String, File> files,final HttpRequestCallBack httpRequestCallback){
		 http.configCurrentHttpCacheExpiry(TIME_OUT);//设置超时时间
	        LogUtils.d(fullUrl(path));
	        RequestParams requestParams = assemblyPostRequestParams(params,files);
	      
	        http.send(HttpMethod.POST, fullUrl(path), requestParams, new RequestCallBack<String>() {//接口回调  
	        	@Override
	        	public void onStart() {
	        		httpRequestCallback.onStartCallBack();
	        	}
	        	
	        	@Override
	        	public void onLoading(long total, long current, boolean isUploading) {
	        		httpRequestCallback.onLoadingCallBack(total, current, isUploading); 
	        	}
	        	
	            @Override  
	            public void onFailure(HttpException error, String msg) {  
	                httpRequestCallback.onFailureCallBack(error, msg);  
	            }  
	  
	            @Override  
	            public void onSuccess(ResponseInfo<String> info) {  
	                httpRequestCallback.onSuccessCallBack(info.result);
	            } 
	        });      	    	
		
	}
    
	/**
	 * 下载文件
	 * @param path
	 * @param target
	 * @param httpRequestCallback
	 */
	public void doDownloadRequest(String path,String target,final RequestCallBack requestCallBack){
		http.configCurrentHttpCacheExpiry(TIME_OUT);//设置超时时间  
		LogUtils.d(fullUrl(path));
		http.download(path, target, new RequestCallBack<File>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				requestCallBack.onFailure(arg0, arg1);
				
			}

			@Override
			public void onSuccess(ResponseInfo<File> arg0) {
				requestCallBack.onSuccess(arg0);
			}
		});
		
		}
	
}
